#!/usr/bin/python 
# coding=utf-8 

import requests
import sys
from pymongo import MongoClient
import logging
import json
import getopt
import subprocess
import  sys,os
reload(sys)
sys.setdefaultencoding("utf-8")

# 获取配置文件
parentdir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.insert(0,parentdir)  
from config.config import BYDK_HALLSWITCHDB_ADDR, BYDK_HALLSWITCHDB_USER, BYDK_HALLSWITCHDB_PASS

def db_conn(mogdb_addr, mogdb_user, mogdb_pass):
    # 数据库配置
    CONN_ADDR1 = mogdb_addr
    username = mogdb_user
    password = mogdb_pass

    # 获取mongoclient 
    client = MongoClient([CONN_ADDR1])
    # 授权. 这里的user基于admin数据库授权 
    client.admin.authenticate(username, password)
    return client

def get_switch(swId):
    swId = int(swId)
    onlines_list = []

    # 查询语句  
    sql_query = {"id": swId}
    sql_ok = {"_id":0}

    client = db_conn(BYDK_HALLSWITCHDB_ADDR, BYDK_HALLSWITCHDB_USER, BYDK_HALLSWITCHDB_PASS)
    res = client.bydk_bus.funcswitch.find_one(sql_query, sql_ok)
    logging.info("{0} {1} {2}".format(sql_query, sql_ok, res))
    return res

if __name__ == "__main__":
    # 定义日志
    log_filename='/data/scripts/bydk/logs/get_hall_switch.log'
    log_format='%(filename)s [%(asctime)s] [%(levelname)s] %(message)s'
    log_datetime='%Y-%m-%d %H:%M:%S'
    logging.basicConfig(filename=log_filename,filemode='a',format=log_format,datetime=log_datetime,level=logging.INFO)

    try:
        opts,args = getopt.getopt(sys.argv[1:],"i:")
    except getopt.GetoptError as err:
        print 'get_hall_switch.py -i <switchId>'
        sys.exit(2)
    for op, value in opts:
        if op in ("-i",):
            hall_switch = value

    res_switch = get_switch(hall_switch)
    if res_switch:
        print(json.dumps(res_switch))
    else:
        print(json.dumps({"msg":"switch {0} is not exist.".format(hall_switch)}))

